package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.code.BusinessBizCode;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.system.dao.SysDictDataDao;
import com.ruoyi.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

/**
 * 字典 业务层处理
 *
 * @author wintersnow
 * @since 1.0  2020-12-11
 */
@Transactional(readOnly = true)
@Service
public class SysDictDataServiceImpl implements ISysDictDataService {

    @Autowired
    private SysDictDataDao dictDataDao;

    /**
     * 根据条件分页查询字典数据
     *
     * @param req 字典数据信息
     * @return 字典数据集合信息
     */
    @Override
    public Page<SysDictData> selectDictDataList(SysDictData req) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (StringUtils.isNotNull(pageDomain.getPageNum()) && StringUtils.isNotNull(pageDomain.getPageSize())) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        }
        Specification<SysDictData> example = new Specification<SysDictData>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<SysDictData> root,
                                         CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (StringUtils.isNoneBlank(req.getDictLabel())) {
                    Predicate pre = cb.like(root.get("dictLabel").as(String.class), "%" + req.getDictLabel() + "%");
                    list.add(pre);
                }
                if (StringUtils.isNoneBlank(req.getDictType())) {
                    Predicate pre = cb.equal(root.get("dictType").as(String.class), req.getDictType());
                    list.add(pre);
                }
                if (StringUtils.isNoneBlank(req.getStatus())) {
                    Predicate pre = cb.equal(root.get("status").as(String.class), req.getStatus());
                    list.add(pre);
                }
                if (list.isEmpty()) {
                    return null;
                }
                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        Pageable pageable = PageRequest.of(pageDomain.getPageNo(), pageDomain.getPageSize(), Sort.Direction.DESC, Optional.ofNullable(pageDomain.getOrderByColumn()).orElse("createTime"));
        Page<SysDictData> page = dictDataDao.findAll(example, pageable);
        return page;
    }

    /**
     * 根据字典类型和字典键值查询字典数据信息
     *
     * @param dictType  字典类型
     * @param dictValue 字典键值
     * @return 字典标签
     */
    @Override
    public String selectDictLabel(String dictType, String dictValue) {
        SysDictData sysDictData = dictDataDao.findByDictTypeAndDictValue(dictType, dictValue).orElse(new SysDictData());
        return sysDictData.getDictLabel();
    }

    /**
     * 根据字典数据ID查询信息
     *
     * @param dictCode 字典数据ID
     * @return 字典数据
     */
    @Override
    public SysDictData selectDictDataById(Long dictCode) {
        SysDictData sysDictData = dictDataDao.findById(dictCode).orElse(new SysDictData());
        return sysDictData;
    }

    /**
     * 批量删除字典数据信息
     *
     * @param dictCodes 需要删除的字典数据ID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteDictDataByIds(Long[] dictCodes) {
        List<SysDictData> sysDictDataList = dictDataDao.findByDictCodeIn(Arrays.asList(dictCodes));
        dictDataDao.deleteAll(sysDictDataList);
        DictUtils.clearDictCache();
        return BusinessBizCode.OPTION_SUCCESS.getCode();
    }

    /**
     * 新增保存字典数据信息
     *
     * @param dictData 字典数据信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertDictData(SysDictData dictData) {
        dictData.setCreateTime(new Date());
        SysDictData save = dictDataDao.save(dictData);
        if (null != save) {
            DictUtils.clearDictCache();
        }
        return BusinessBizCode.OPTION_SUCCESS.getCode();
    }

    /**
     * 修改保存字典数据信息
     *
     * @param dictData 字典数据信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateDictData(SysDictData dictData) {
        SysDictData save = dictDataDao.save(dictData);
        if (null != save) {
            DictUtils.clearDictCache();
        }
        return BusinessBizCode.OPTION_SUCCESS.getCode();
    }
}
